package com.jiyun.behavior.service.ipl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiyun.behavior.mapper.ApReadBehaviorMapper;
import com.jiyun.behavior.service.ApReadBehaviorService;
import com.usian.model.behavior.ApReadBehavior;
import com.usian.model.behavior.ReadBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

public class ApReadBehaviorServiceipl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements ApReadBehaviorService {


    @Autowired
    private ApReadBehaviorMapper apReadBehaviorMapper;

    @Override
    public ResponseResult yueduxingwei(ReadBehaviorDto dto) {

        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<ApReadBehavior> qw=new LambdaQueryWrapper<>();
        qw.eq(ApReadBehavior::getArticleId,dto.getArticleId());
        ApReadBehavior apReadBehavior = apReadBehaviorMapper.selectOne(qw);
        if (apReadBehavior!=null){
            LambdaUpdateWrapper<ApReadBehavior> qw1=new LambdaUpdateWrapper<>();
            qw1.set(ApReadBehavior::getUpdatedTime,new Date());
            qw1.set(ApReadBehavior::getPercentage,dto.getPercentage());
            qw1.set(ApReadBehavior::getLoadDuration,dto.getLoadDuration());
            qw1.set(ApReadBehavior::getReadDuration,dto.getReadDuration());
            apReadBehaviorMapper.update(apReadBehavior,qw1);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        apReadBehavior.setCount(apReadBehavior.getCount()+dto.getCount());
        apReadBehavior.setUpdatedTime(new Date());
        apReadBehavior.setLoadDuration(dto.getLoadDuration());
        apReadBehavior.setPercentage(dto.getPercentage());
        apReadBehavior.setReadDuration(dto.getReadDuration());
        apReadBehaviorMapper.insert(apReadBehavior);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
